package cn.hn3l.controler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import cn.hn3l.service.implement.LoginService;

/**登录控制器
 * url=login/login.html
 * */
public class DoLogin implements Controller {
	@Resource
	private LoginService loginService;
	@Resource
	private ModelAndView mav;
	public ModelAndView getMav() {
		return mav;
	}

	public void setMav(ModelAndView mav) {
		this.mav = mav;
	}

	private static Logger log = Logger.getLogger(DoLogin.class.getName());
	public LoginService getLoginService() {
		return loginService;
	}
	
	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		// TODO Auto-generated method stub
//		ModelAndView mav = new ModelAndView();
			//如果用户使用get方法
			if(request.getMethod().equals("GET")){
				return proGetRequest(request,response,mav);
			}else if(request.getMethod().equals("POST")){
				
					return proPostRequest(request,response,mav);
				}
//			Thread.currentThread().getName();
			return mav;
		}
	
	
private ModelAndView proPostRequest(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) {
		// TODO Auto-generated method stub
    //判断用户所输入的验证码
    if(loginCaptchaError(request, mav))
        return mav;
	//登录失败返回服务界面
    if (loginError(request, mav))
        return mav;
    //当登录成功时
	try {
		loginSuccess(mav,request,response);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
	}

    private boolean loginCaptchaError(HttpServletRequest request, ModelAndView mav) {
        int inCaptcha;
        try {
            inCaptcha = Integer.parseInt(request.getParameter("captcha"));
        }catch (Exception e){
            e.printStackTrace();
            mav.addObject("login_faild", "验证码为空错误");
            mav.setViewName("/login/login_error.jsp");
            log.warning("登录失败，验证码为空");
            return true;
        }
        //当验证码不为空的情况下
        HttpSession session = request.getSession();
        log.warning("客户机的验证码：" + inCaptcha);
        int sysCaptcha = (int) session.getAttribute("sResult");
        log.warning("服务器的验证码：" + sysCaptcha);
        if (inCaptcha != sysCaptcha){
            mav.addObject("login_faild", "验证码错误");
            mav.setViewName("/login/login_error.jsp");
            log.warning("登录失败，验证码错误");
            return true;
        }
        return false;
    }

    private boolean loginError(HttpServletRequest request, ModelAndView mav) {
		try {
			if(!loginService.isRight(request)){
                mav.addObject("login_faild", "账户名或密码错误");
                mav.setViewName("/login/login_error.jsp");
                log.warning("登录失败");
                return true;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
    }

//		
	/**处理用户get请求*/
	private ModelAndView proGetRequest(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) {
		// TODO Auto-generated method stub
		System.out.print("服务开始");
		mav.setViewName("/login/login.jsp");
		HttpSession session = request.getSession();
		//当用户未登陆时
		if(session.getAttribute("username") == null){
			System.out.println("session为空");
		}
		//当用户已登录时
		else{
			//用户注销请求
			if(request.getParameter("exit") != null){
				//从session中拿掉username
				session.removeAttribute("username");
				System.out.println("session已清空");
				try {
					PrintWriter pw = response.getWriter();
					pw.println(1);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}
		}
		return mav;
	}

	private void loginSuccess(ModelAndView mav, HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		log.info("登录成功");
		//把已经登录的用户放到session里
		HttpSession session = request.getSession();
	
		session.setAttribute("username", request.getParameter("userName"));
        try {
            PrintWriter writer = response.getWriter();
            writer.print(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
		
	}

}
